import re

from flask import Flask, render_template,request,jsonify,make_response
from robot import robot
from werobot.contrib.flask import make_view

from obcs import timeFmt

from config import obcos,moonreader_token,right_token,simp_read_token

app = Flask(__name__)

app.add_url_rule(rule='/api/wechat',endpoint='werobot',view_func=make_view(robot),methods=['GET', 'POST'])


# werobot cos-python-sdk-v5 Flask

@app.route("/")
def index_html():
    f = open("index.html")
    data = f.read()
    f.close()
    resp = make_response(data)
    resp.headers = {"Content-Type": "text/html"}
    return resp


fchars = r"[\/\\\:\*\?\"\<\>\|\#\^\[\]]" # obsidian 文件名非法字符 * " \ / < > : | ? 链接失效 # ^ [ ] |

#
@app.route("/headers")
def headers_test():
        hs = request.headers.get('Token')
        hd = request.headers
        print(hs)
        if(str(hs)==right_token):
            r_str = obcos.append_memos_in_daily("函数计算运行成功")
            return str(hd) + '\n\nToken=' + str(hs)
        return 'Auth Error'

# OB fv 悬浮球 UESD Simp Store into folder -> 支持类文件/fv/
@app.route("/ob/fv", methods=['POST'])
def fv_store():
    hs = request.headers.get('Token')
    hp = request.headers.get('Content-Type')
    file_bytes = request.data
    if ( str(hs)!= right_token):
        return make_response('Auth Error',401)
    if(hp=='text/plain'):
        obcos.append_memos_in_daily(file_bytes.decode("utf-8"))
    elif(hp=='application/octet-stream'):
        file_key = obcos.daily_attachment_file_dir() + timeFmt("%Y%m%d%H%M%S") + ".jpg"
        obcos.store(file_key, file_bytes)
        obcos.append_memos_in_daily("![]({})".format(file_key))
    else:
        return make_response('Do not supposed!',412)
    return "Success"

# OB TODAY GET/POST
@app.route("/ob/today", methods=['GET', 'POST'])
def today():
    hs = request.headers.get('Token')
    if ( str(hs)!= right_token):
        return 'Auth Error'
    if (request.method == 'GET'):
        r_json =obcos.today_daily_json()
        r_list = []
        r_list.append(r_json)
        return jsonify(r_list)
    if (request.method == 'POST'):
        json_data = request.get_json()
        r_str = obcos.append_memos_in_daily(json_data['content'])
        return "Success"
    return "Unallowed Request Method"

# OB 3 DAYS GET
@app.route("/ob/recent", methods=['GET'])
def recent():
    if ( str(request.headers.get('Token'))!= right_token):
        return 'Auth Error'
    return jsonify(obcos.recent_days_daily())

# OB 1 TODAY update all
@app.route("/ob/today/all", methods=['POST'])
def today_modify():
    if ( str(request.headers.get('Token'))!= right_token):
        return 'Auth Error'
    json_data = request.get_json()
    r_str = obcos.store(obcos.daily_file_key(),json_data['content'])
    return "Success"

# OB 图片 临时访问 url 获取  -> 返回一个 s3 临时访问 url 
# 暂时未使用
# @app.route("/ob/images")
# def ob_images():
#     if ( str(request.headers.get('Token'))!= right_token):
#         return 'Auth Error'
#     file_key = request.args.get('key')
#     return obcos.tem_url(file_key)

# moonreader readwise api like 
@app.route("/ob/moonreader",methods=["POST"])
def moonreader():
    # print(request.headers)
    moonreader_token_str = "Token " + moonreader_token
    if(str(request.headers.get("Authorization"))!=moonreader_token_str):
        return make_response("Auth Error!",401)
    json_data = request.get_json()['highlights'][0]
    text = '文: ' + str(json_data.get('text')) \
        + '\n批: ' + str(json_data.get('note')) \
        + '\n于: ' + timeFmt('%Y-%m-%d %H:%M') + '\n\n---\n'
    file_key = "支持类文件/MoonReader/" +  re.sub(fchars, "_", str(json_data.get('title'))) + '.md'
    if(obcos.check(file_key)):
        obcos.append(file_key,text)
    else:
        yaml = '---\n' + 'title: ' + str(json_data.get('title')) + \
                     '\nauthor: ' + str(json_data.get('author')) + '\n' + '---\n' + \
                '书名: ' + str(json_data.get('title')) + \
                '\n作者: ' + str(json_data.get('author')) + '\n简介: \n评价: \n\n---\n'
        obcos.append(file_key,yaml + text)
    return make_response('Success',200)

# SimpRead WebHook Used 
@app.route("/webhook",methods=["POST"])
def webhook():
    if(str(request.headers.get('Token'))!=simp_read_token):
        return make_response('Auth Error',401)
    json_data = request.get_json()
    serverTime = timeFmt("%Y%m%d%H%M")
    yaml = "---\ntitle: "+ json_data.get('title') + "\nsctime: " + serverTime + "\n---\n"
    file_str = yaml + "[[简悦WebHook生成]]\n生成时间: " +serverTime + "\n原文: " + json_data.get('url') + "\n标题: " + json_data.get('title') + \
        "\n描述: " + json_data.get('desc') + "\n标签: " + json_data.get('tags') + "\n内容: \n" + json_data.get('content')
    # file_key 支持类文件/SimpRead/json.get("title") + time + .md
    file_key = "支持类文件/SimpRead/" + re.sub(fchars, "_", json_data.get('title')) + " "+ serverTime + '.md'
    file_bytes = bytes(file_str, encoding="utf8")
    obcos.store(file_key, file_bytes)
    return 'Success'


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=9000)

# app.run(host='0.0.0.0',port=9000,debug=True)
